<?php
namespace Home\Controller;
use Common\Controller\CommonController;

/**
 * 广告图片
 * @author 张亚伟 <zhangyw@zhijin101.com>
 */
class AdController extends CommonController
{
    private $type_arr = ['1'=>'首页底部', '2'=>'签到商品'];
    public function index()
    {
        $model = M('ad');
        $Count = $model->count();
        $Page = new \Think\Pager($Count,10);
        $show = $Page->showhtml();
        $where = [];

        $list = $model->where($where)->limit($Page->firstRow.','.$Page->listRows)->order('id desc')->select();
        if($list){
            foreach($list as $key=>&$row){
                $row['type'] = isset($this->type_arr[$row['type']]) ? $this->type_arr[$row['type']] : '';
            }
        }
        $this->assign('page',$show);
        $this -> assign('list', $list);
        $this -> display();
    }

    public function add()
    {
        if(IS_POST){
            $data = I('post.');
            if(empty($data['type'])){
                $this->ajaxReturn(array('s'=>false,'m'=>'请选择类型'));
            }
            if(empty($data['img'])){
                $this->ajaxReturn(array('s'=>false,'m'=>'请上传图片'));
            }

            $data['img'] = isset($data['img']) ? $data['img'] : '';
            $model = M('ad');

            $id = $model->add($data);
            if($id){
                $this->ajaxReturn(array('s'=>true,'m'=>'添加成功', 'url'=>U('index')));
            }else{
                $this->ajaxReturn(array('s'=>false,'m'=>'添加失败!'));
            }
        }else{
            $this->assign('type_arr', $this->type_arr);
            $this->display();
        }
    }

    public function edit()
    {
        $id = I('id');
        if(IS_POST){
            $data = I('post.');
            if(empty($data['type'])){
                $this->ajaxReturn(array('s'=>false,'m'=>'请选择类型'));
            }
            if(empty($data['img'])){
                $this->ajaxReturn(array('s'=>false,'m'=>'请上传图片'));
            }
            $data['img'] = isset($data['img']) ? $data['img'] : '';

            $model = M('ad');

            $res = $model->where(['id'=>$id])->save($data);
            if($res!==false){
                $this->ajaxReturn(array('s'=>true,'m'=>'修改成功', 'url'=>U('index')));
            }else{
                $this->ajaxReturn(array('s'=>false,'m'=>'修改失败!'));
            }
        }else{
            $info = M('ad')->where(['id'=>$id])->find();
            $this->assign('info', $info);
            $this->assign('type_arr', $this->type_arr);
            $this->display();
        }
    }

    public function del(){
        $id = I('id');
        $res = M('ad')->where(['id'=>$id])->delete();
        if($res){
            $this->ajaxReturn(array('s'=>true,'m'=>'删除成功', 'url'=>U('index')));
        }else{
            $this->ajaxReturn(array('s'=>false,'m'=>'删除失败!'));
        }
    }
}
